package bar.dark.lee.select;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.BackgroundColorSpan;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.TextView;
import bar.dark.lee.BDConstents;
import bar.dark.lee.MainActivity;
import bar.dark.lee.R;
import bar.dark.lee.SuperActivity;
import bar.dark.lee.cashdrawing.CashTabActivity;
import bar.dark.lee.common.BDTextView;
import bar.dark.lee.common.BDUtil;
import bar.dark.lee.common.DBSQLite;
import bar.dark.lee.common.BDUtil.WeekDayClass;
import bar.dark.lee.common.DBSQLite.ParseSelectData;
import bar.dark.lee.insert.InsertTabActivity;
import bar.dark.lee.select.search.SearchActivity;
import bar.dark.lee.setting.TipInfoActivity;
import bar.dark.lee.setting.TipsActivity;
import bar.dark.lee.stats.StatsActivity;
import bar.dark.lee.stats.StatsAssetActivity;
import bar.dark.lee.stats.StatsCategoryData;
import bar.dark.lee.widget.WidgetGetSqlQuery;

public class SelectActivity extends SuperActivity
{
	public static String SELECT_DATA = "select_data";
	
	private DBSQLite sql;
	
	private ExpandableListView listView;
	
	private View resultView;
	
	private int tempDate = -1;
	
	private ArrayList<SelectDayData> dayList;
	
	private ArrayList<CheckDate> totalSelect = new ArrayList<CheckDate>();
	private int inoutFlag;
	private int inoutYear;
	private int inoutMonth;
	private boolean mainFlag;
	
	private int categoryFlag;
	private int categoryYear;
	private int categoryMonth;
	private String categoryStr;
	private String moneykindStr;
	private int typeFlag;
	private int assetFlag;
	
	private int year;
	private int month;
	private int date;
	
	private String firstDate;
	private String lastDate;
	
//	private int totalIn;
//	private int totalOut;
//	private int totalCard;
	private BigDecimal totalIn;
	private BigDecimal totalOut;
	private BigDecimal totalCard;
	
	private int inMoneyColor;
	private int outMoneyColor;
	private int postMoneyColor;
	private int cashDrawingColor;
	
	private SharedPreferences pref;
	private SharedPreferences.Editor editor;
	
	private ArrayList<IsOpenData> openArrayList = null;
	
	private boolean searchFlag;
	private String searchType;
	private String searchStartDate;
	private String searchEndDate;
	private String searchCategoryOut;
	private String searchCategoryIn;
	private String searchCategoryMove;
	private String searchBankBook;
	private String searchCheckCard;
	private String searchCreditCard;
	private String searchMemo;
	
	private ArrayList<String> moneyKinds = new ArrayList<String>();
	
	private int fanOkNoFlag = 0;
	private String [] categorys;
	
	private WidgetGetSqlQuery mainQuery;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		isAdFlag = false;
		
		super.onCreate(savedInstanceState);
		
		sql = DBSQLite.getInstance(this);
		
		setTitle("내역 조회");
		
		setContentView(R.layout.select_activity);
		
		setFindView();
		initClickListener();
		initDataSetting();
		
		Calendar calendar = Calendar.getInstance();
		year = calendar.get(Calendar.YEAR);
		month = calendar.get(Calendar.MONTH);
		date = calendar.get(Calendar.DAY_OF_MONTH);
		
		Resources resources = getResources();
		inMoneyColor = resources.getColor(R.color.inmoney);
		outMoneyColor = resources.getColor(R.color.outmoney);
		postMoneyColor = resources.getColor(R.color.postmoney);
		cashDrawingColor = resources.getColor(R.color.cashdrawingmoney);
		
		openArrayList = new ArrayList<IsOpenData>();
	}
	
	@Override
	protected void onResume()
	{
		super.onResume();
		new ShowDialog().execute(null);
	}
	
	@Override
	protected void onPause()
	{
		super.onPause();
		
		setIsOpenData();
	}

	private void setIsOpenData()
	{
		if (listView == null)
		{
			return;
		}
		
		IsOpenData data = new IsOpenData(listView.getCount());
		
		String date = ((TextView) findViewById(R.id.select_text_today)).getText().toString();
		
		data.setDate(date);
		
		for (int i = 0; i < openArrayList.size(); i++)
		{
			IsOpenData tempData = openArrayList.get(i);
			
			if (date.equals(tempData.getDate()))
			{
				openArrayList.remove(i);
			}
		}
		
		int [] isOpenArray = data.getIsOpenArry();
		
		ExpandableListAdapter adapter = listView.getExpandableListAdapter();
		
		if (adapter == null)
		{
			return;
		}
		
		for (int i = 0; i < adapter.getGroupCount(); i++)
		{
			if (listView.isGroupExpanded(i))
			{
				isOpenArray[i] = 1;
			}
			else
			{
				isOpenArray[i] = 0;
			}
		}
		
		openArrayList.add(data);
	}
	
	@Override
	protected void onStop()
	{
		super.onStop();
	}

	private void setFindView()
	{
		listView = (ExpandableListView) findViewById(R.id.selectListView);
		listView.setGroupIndicator(null);
		
		LayoutInflater li = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
		resultView = li.inflate(R.layout.view_no_result, null);
	}
	
	private void initDataSetting()
	{
		Intent intent = getIntent();
		
		totalSelect = intent.getParcelableArrayListExtra("TotalSelect");
		inoutFlag = intent.getIntExtra(StatsActivity.STATS_MONTH_FLAG, -1);
		inoutYear = intent.getIntExtra(StatsActivity.SELECT_YEAR, -1);
		inoutMonth = intent.getIntExtra(StatsActivity.SELECT_MONTH, -1);
		categoryFlag = intent.getIntExtra(StatsActivity.STATS_CATEGORY_FLAG, -1);
		categoryYear = intent.getIntExtra(StatsActivity.SELECT_YEAR, -1);
		categoryMonth = intent.getIntExtra(StatsActivity.SELECT_MONTH, -1);
		categoryStr = intent.getStringExtra(StatsActivity.SELECT_CATEGORY);
		moneykindStr = intent.getStringExtra(StatsActivity.SELECT_MONEYKIND);
		typeFlag = intent.getIntExtra(StatsAssetActivity.TYPE_FLAG, 0);
		
		mainFlag = intent.getBooleanExtra(MainActivity.SELECT_FLAG, false);
		mainQuery = new WidgetGetSqlQuery(superContext);
		
		if (mainFlag)
		{
			String mainStartDate = getIntent().getStringExtra(MainActivity.START_DATE);
			String mainEndDate = getIntent().getStringExtra(MainActivity.END_DATE);
			
			int mainYear = getIntent().getIntExtra(MainActivity.MAIN_TO_YEAR, year);
			int mainMonth = getIntent().getIntExtra(MainActivity.MAIN_TO_MONTH, month);
			int mainDay = getIntent().getIntExtra(MainActivity.MAIN_TO_DAY, date);
			
			mainQuery.setDate(mainYear, mainMonth, mainDay);
			
			year = mainQuery.getYear();
			month = mainQuery.getMonth();
			date = mainQuery.getDay();
			
			firstDate = mainStartDate;
			lastDate = mainEndDate;
		}
		
		searchFlag = intent.getBooleanExtra(SearchActivity.SEARCH_FLAG, false);
		
		if (searchFlag)
		{
			searchType = intent.getStringExtra(SearchActivity.SEARCH_TYPE);
			searchStartDate = intent.getStringExtra(SearchActivity.SEARCH_START_DATE);
			searchEndDate = intent.getStringExtra(SearchActivity.SEARCH_END_DATE);
			searchCategoryOut = intent.getStringExtra(SearchActivity.SEARCH_CATEGORY_OUT);
			searchCategoryIn = intent.getStringExtra(SearchActivity.SEARCH_CATEGORY_IN);
			searchCategoryMove = intent.getStringExtra(SearchActivity.SEARCH_CATEGORY_MOVE);
			searchBankBook = intent.getStringExtra(SearchActivity.SEARCH_BANKBOOK);
			searchCheckCard = intent.getStringExtra(SearchActivity.SEARCH_CHECKCARD);
			searchCreditCard = intent.getStringExtra(SearchActivity.SEARCH_CREDITCARD);
			searchMemo = intent.getStringExtra(SearchActivity.SEARCH_MEMO);
		}
	}
	
	private void setSelectMonthData()
	{
		dayList = new ArrayList<SelectDayData>();
		
		tempDate = -1;
		
		totalIn = BigDecimal.ZERO;
		totalOut = BigDecimal.ZERO;
		totalCard = BigDecimal.ZERO;
		
		setSelectDayData();
	}
	
	private void setTextResult() 
	{
		if (!searchFlag && totalSelect == null) 
		{
			pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
			int startDate = Integer.parseInt(pref.getString(BDConstents.START_DATE, "1"));
			
			if (startDate == 1)
			{
				((TextView)findViewById(R.id.select_text_today)).setText(year + "년 " + (month + 1) + "월");
			}
			else
			{
				if (month+1 == 1) 
				{
					if (date < startDate && statsFlag)
					{
						String yearStr = year+"";
						((TextView)findViewById(R.id.select_text_today)).setText(((year-1)+"").substring(2, yearStr.length()) + "년12월 ~ " 
								+ (year+"").substring(2, yearStr.length()) + "년1월");
					}
					else
					{
						((TextView)findViewById(R.id.select_text_today)).setText(year + "년 " + (month + 1) + "~" + (month + 2) + "월");
					}
				}
				else if (month+1 == 12)
				{
					if (date < startDate && statsFlag)
					{
						((TextView)findViewById(R.id.select_text_today)).setText(year + "년 " + (month) + "~" + (month + 1) + "월");
					}
					else
					{
						String yearStr = year+"";
						((TextView)findViewById(R.id.select_text_today)).setText(((year)+"").substring(2, yearStr.length()) + "년12월 ~ " 
								+ ((year+1)+"").substring(2, yearStr.length()) + "년1월");
					}
				}
				else
				{
					if (date < startDate && statsFlag)
					{
						((TextView)findViewById(R.id.select_text_today)).setText(year + "년 " + (month) + "~" + (month + 1) + "월");
					}
					else
					{
						((TextView)findViewById(R.id.select_text_today)).setText(year + "년 " + (month + 1) + "~" + (month + 2) + "월");
					}
				}
			}
			
			// 통계의 이동 카테고리로 인해서 수입 지출을 안보이게 한다. 그리고 월간이동을 넣어준다.
			if (categoryFlag == StatsActivity.STATS_MOVE || 
					(categoryFlag == StatsActivity.STATS_ASSET_MANAGER && typeFlag == 2))
			{
				((TextView)findViewById(R.id.select_text_in_subject)).setVisibility(View.INVISIBLE);
				((TextView)findViewById(R.id.select_text_out_subject)).setVisibility(View.INVISIBLE);
				((TextView)findViewById(R.id.select_text_card_subject)).setText("월간이동");
			}
		}
		else 
		{
			if (searchFlag)
			{
				try
				{
					int [] startDates = BDUtil.getDateSet(searchStartDate);
					int [] endDates = BDUtil.getDateSet(searchEndDate);
					
					String startYear = startDates[0] + "";
					String endYear = endDates[0] + "";
					
					startYear = startYear.substring(2, startYear.length());
					endYear = endYear.substring(2, endYear.length());
					
					String startMonth = startDates[1] + "";
					String endMonth = endDates[1] + "";
					
					if (Integer.parseInt(startMonth) < 10)
					{
						startMonth = "0" + startMonth;
					}
					if (Integer.parseInt(endMonth) < 10)
					{
						endMonth = "0" + endMonth;
					}
					
					String startDay = startDates[2] + "";
					String endDay = endDates[2] + "";
					
					if (Integer.parseInt(startDay) < 10)
					{
						startDay = "0" + startDay;
					}
					if (Integer.parseInt(endDay) < 10)
					{
						endDay = "0" + endDay;
					}
					
					((TextView) findViewById(R.id.select_text_today)).
					setText(startYear + "." + startMonth + "." + startDay+ " ~ " 
					+ endYear + "." + endMonth + "." + endDay + "");
				} catch (Exception e)
				{
					((TextView) findViewById(R.id.select_text_today)).setText(searchStartDate + " ~ " + searchEndDate);
				}
			}
			else
			{
				findViewById(R.id.select_layout_top).setVisibility(View.GONE);
			}
			
			((TextView)findViewById(R.id.select_text_in_subject)).setText("조회기간수입");
			((TextView)findViewById(R.id.select_text_out_subject)).setText("조회기간지출");
			((TextView)findViewById(R.id.select_text_card_subject)).setText("조회기간카드");
		}
		
		((TextView)findViewById(R.id.select_text_in)).setText(BDUtil.getWon(totalIn.toString()));
		((TextView)findViewById(R.id.select_text_out)).setText(BDUtil.getWon(totalOut.toString()));
		((TextView)findViewById(R.id.select_text_card)).setText(BDUtil.getWon(totalCard.toString()));
		
		// 통계의 이동 카테고리로 인해서 수입,지출을 안보이게 한다.
		if (categoryFlag == StatsActivity.STATS_MOVE || 
				(categoryFlag == StatsActivity.STATS_ASSET_MANAGER && typeFlag == 2))
		{
			((TextView)findViewById(R.id.select_text_in)).setVisibility(View.INVISIBLE);
			((TextView)findViewById(R.id.select_text_out)).setVisibility(View.INVISIBLE);
			((TextView)findViewById(R.id.select_text_card)).setTextColor(cashDrawingColor);
		}
	}
	
	/**
	 * 월 단위 쿼리 반환.
	 * @param year
	 * @param month
	 * @return
	 */
	private String getDateForMonth(int year, int month) 
	{
		String m = "" + (month+1);
		
		if (month+1 < 10) 
		{
			m = "0" + (m);
		}
		
		String date = year+"" + m;
		String query = " WHERE date >= " + (date+"01") + " and date <= " + (date+"31") + " ";
		return query;
	}
	
	/**
	 * 사용자 시작일 지정 월 단위 쿼리 반환.
	 * @param year
	 * @param month
	 * @return
	 */
	private String getDateForMonthUser(int year, int month, int startDate, boolean statsFlag) 
	{
		if (month+1 == 1) 
		{
			if (date < startDate && statsFlag)
			{
				String beforeMonth = (year-1) + "" + "12";
				String currentMonth = year + "" + "01";
				
				String m = "" + (startDate);
				
				if (startDate < 10) 
				{
					m = "0" + startDate;
				}
				
				String beforeDate = m;
				
				m = "" + (startDate-1);
				
				if (startDate-1 < 10) 
				{
					m = "0" + (m);
				}
				
				String currentDate = m;
				
				firstDate = beforeMonth + beforeDate;
				lastDate = currentMonth + currentDate;
				String query = " WHERE date >= " + firstDate 
								+ " and date <= " + lastDate + " ";
				return query;
			}
			else
			{
				String beforeMonth = year + "" + "01";
				String currentMonth = year + "" + "02";
				
				String m = "" + (startDate);
				
				if (startDate < 10) 
				{
					m = "0" + startDate;
				}
				
				String beforeDate = m;
				m = "" + (startDate-1);
				
				if (startDate-1 < 10) 
				{
					m = "0" + (m);
				}
				
				String currentDate = m;
				
				firstDate = beforeMonth+beforeDate;
				lastDate = currentMonth+currentDate;
				String query = " WHERE date >= " + firstDate 
								+ " and date <= " + lastDate + " ";
				return query;
			}
		}
		else if (month+1 == 12)
		{
			if (date < startDate && statsFlag)
			{
				String beforeMonth = year + "" + "11";
				String currentMonth = year + "" + "12";
				
				String m = "" + (startDate);
				
				if (startDate < 10) 
				{
					m = "0" + startDate;
				}
				
				String beforeDate = m;
				
				m = "" + (startDate-1);
				
				if (startDate-1 < 10) 
				{
					m = "0" + (m);
				}
				
				String currentDate = m;
				
				firstDate = beforeMonth + beforeDate;
				lastDate = currentMonth + currentDate;
				String query = " WHERE date >= " + firstDate 
								+ " and date <= " + lastDate + " ";
				return query;
			}
			else
			{
				String beforeMonth = year + "" + "12";
				String currentMonth = (year+1) + "" + "01";
				
				String m = "" + (startDate);
				
				if (startDate < 10) 
				{
					m = "0" + startDate;
				}
				
				String beforeDate = m;
				
				m = "" + (startDate-1);
				
				if (startDate-1 < 10) 
				{
					m = "0" + (m);
				}
				
				String currentDate = m;
				
				firstDate = beforeMonth + beforeDate;
				lastDate = currentMonth + currentDate;
				
				String query = " WHERE date >= " + firstDate 
								+ " and date <= " + lastDate + " ";
				return query;
			}
		}
		else
		{
			if (date < startDate && statsFlag)
			{
				String m = "" + (month);
				
				if (month < 10) 
				{
					m = "0" + (m);
				}
				
				String beforeMonth = year+"" + m;
				m = "" + (month+1);
				
				if (month+1 < 10) 
				{
					m = "0" + (m);
				}
				
				String currentMonth = year+"" + m;
				m = "" + (startDate);
				
				if (startDate < 10) 
				{
					m = "0" + startDate;
				}
				
				String beforeDate = m;
				m = "" + (startDate-1);
				
				if (startDate-1 < 10) 
				{
					m = "0" + (m);
				}
				
				String currentDate = m;
				
				firstDate = beforeMonth + beforeDate;
				lastDate = currentMonth + currentDate;
				String query = " WHERE date >= " + firstDate 
								+ " and date <= " + lastDate + " ";
				return query;
			}
			else
			{
				String m = "" + (month+1);
				
				if (month+1 < 10) 
				{
					m = "0" + (m);
				}
				
				String beforeMonth = year+"" + m;
				m = "" + (month+2);
				
				if (month+2 < 10) 
				{
					m = "0" + (m);
				}
				
				String currentMonth = year+"" + m;
				m = "" + (startDate);
				
				if (startDate < 10) 
				{
					m = "0" + startDate;
				}
				
				String beforeDate = m;
				m = "" + (startDate-1);
				
				if (startDate-1 < 10) 
				{
					m = "0" + (m);
				}
				
				String currentDate = m;
				
				firstDate = beforeMonth + beforeDate;
				lastDate = currentMonth + currentDate;
				String query = " WHERE date >= " + firstDate 
								+ " and date <= " + lastDate + " ";
				return query;
			}
		}
	}
	
	private String getDateForSearch(String startDate, String endDate)
	{
		firstDate = startDate;
		lastDate = endDate;
		String query = " WHERE date >= " + startDate + " and date <= " + endDate + " ";
		
		return query;
	}
	
	/**
	 * 체크된 날짜로부터 날짜를 가져와 쿼리문을 반환한다.
	 * @return 넘어온 CheckDate로부터 뽑아낸 날짜 스트링
	 */
	private String getDateForCheckDate() {
		
		String query = " WHERE date in (";
		
		for (int i=0; i < totalSelect.size(); i++) 
		{
			CheckDate data = totalSelect.get(i);
			
			for (int j=0; j < data.getSelectDate().size(); j++) 
			{
				query = query + BDUtil.getDateDB(data.getYear(), data.getMonth(), 
						Integer.parseInt(data.getSelectDate().get(j))) + ", ";
			}
		}
		
		query = query.substring(0, query.lastIndexOf(",")) + ")";
		
		return query;
	}
	
	private boolean statsFlag = true;
	/**
	 * 날짜에 따라서 데이터를 가져와서 셋팅한다.
	 */
	private void setSelectDayData()
	{
		pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
		
		fanOkNoFlag = pref.getInt(BDConstents.FAN_SETTING_OK_NO, 0);
		
		String query = "SELECT * FROM in_out";
		String tempQuery = "";
		
		if (totalSelect != null && totalSelect.size() != 0) 
		{
			query = query + getDateForCheckDate();
		} 
		else 
		{
			int startDate = Integer.parseInt(pref.getString(BDConstents.START_DATE, "1"));
			
			if (inoutMonth != -1)
			{
				if (statsFlag)
				{
					month = inoutMonth;
					
					if (inoutYear != -1)
					{
						year = inoutYear;
						statsFlag = false;
					}
					else
					{
						year = categoryYear;
						statsFlag = false;
					}
				}
			}
			else if (categoryMonth != -1)
			{
				if (statsFlag)
				{
					month = categoryMonth;
					
					if (inoutYear != -1)
					{
						year = inoutYear;
						statsFlag = false;
					}
					else
					{
						year = categoryYear;
						statsFlag = false;
					}
				}					
			}
			
			if (!searchFlag && !mainFlag)
			{
				if (startDate == 1)
				{
					query = query + getDateForMonth(year, month);
				}
				else 
				{
					query = query + getDateForMonthUser(year, month, startDate, statsFlag);
				}
			}
			else if (mainFlag)
			{
				String mainKey = getIntent().getStringExtra(MainActivity.MAIN_KEY);
				int mainNumber = getIntent().getIntExtra(MainActivity.MAIN_NUMBER, 0);
				
				query = mainQuery.getSelectQuery(mainKey, mainNumber);
				
				year = mainQuery.getYear();
				month = mainQuery.getMonth();
				date = mainQuery.getDay();
			}
			else if (searchFlag) // 검색에서 넘어왔을때
			{	
				// 날짜 셋팅
				query = query + getDateForSearch(searchStartDate, searchEndDate);
				
				String searchCategory = "";
				String searchName = "";
				
				boolean outFlag = false;
				boolean inFlag = false;
				boolean moveFlag = false;
				
				if ( ! (searchType == null || searchType.equals("조건 없음") || searchType.equals("목록 없음") || searchType.length() == 0))
				{
					query += "and type in (" + searchType + ") ";
				}
				
				if ( ! (searchCategoryOut == null || searchCategoryOut.equals("조건 없음") || searchCategoryOut.equals("목록 없음") || searchCategoryOut.length() == 0))
				{	
					searchCategory += searchCategoryOut;
					outFlag = true;
				}
				
				if ( ! (searchCategoryIn == null || searchCategoryIn.equals("조건 없음") || searchCategoryIn.equals("목록 없음") || searchCategoryIn.length() == 0))
				{
					if ( ! (searchCategory == null || searchCategory.equals("조건 없음") || searchCategory.equals("목록 없음") || searchCategory.length() == 0))
					{
						searchCategory += ", " + searchCategoryIn;
					}
					else
					{
						searchCategory += searchCategoryIn;
					}
					
					inFlag = true;
				}
				
				if ( ! (searchCategoryMove == null || searchCategoryMove.equals("조건 없음") || searchCategoryMove.equals("목록 없음") || searchCategoryMove.length() == 0))
				{
					if ( ! (searchCategory == null || searchCategory.equals("조건 없음") || searchCategory.equals("목록 없음") || searchCategory.length() == 0))
					{
						searchCategory += ", " + searchCategoryMove;
					}
					else
					{
						searchCategory += searchCategoryMove;
					}
					
					moveFlag = true;
				}
				
				if ( ! (searchCategory == null || searchCategory.equals("조건 없음") || searchCategory.equals("목록 없음") || searchCategory.length() == 0))
				{
					categorys = searchCategory.split(", ");
					
					searchCategory = searchCategory.replaceAll(", ", "', '");
					query += "and category in ('" + searchCategory + "') ";
					
					if (outFlag)
					{
						if (inFlag)
						{
							// 전체
							if (moveFlag)
							{
								
							}
							// 지출, 수입
							else
							{
								query += "and type not in (" + 
										BDConstents.INOUT_TYPE + ", " +
										BDConstents.OUTIN_TYPE + ", " +
										BDConstents.MYBANK_INOUT_TYPE + ") ";
							}
						}
						else
						{
							// 지출, 이동
							if (moveFlag)
							{
								query += "and inmoney in ('0') " +
										"and (outmoney not in ('0') or postmoney not in ('0')) ";
							}
							// 지출
							else
							{
								query += "and type not in (" + 
										BDConstents.INOUT_TYPE + ", " +
										BDConstents.OUTIN_TYPE + ", " +
										BDConstents.MYBANK_INOUT_TYPE + ") ";
								
								query += "and inmoney in ('0') " +
										"and (outmoney not in ('0') or postmoney not in ('0')) ";
							}
						}
					}
					else
					{
						if (inFlag)
						{
							// 수입, 이동
							if (moveFlag)
							{
								query += "and inmoney not in ('0') ";
								
								query += "or type in (" + 
										BDConstents.INOUT_TYPE + ", " +
										BDConstents.OUTIN_TYPE + ", " +
										BDConstents.MYBANK_INOUT_TYPE + ") ";
							}
							// 수입
							else
							{
								query += "and type not in (" + 
										BDConstents.INOUT_TYPE + ", " +
										BDConstents.OUTIN_TYPE + ", " +
										BDConstents.MYBANK_INOUT_TYPE + ") ";
								
								query += "and inmoney not in ('0') ";
							}
						}
						else
						{
							// 이동
							if (moveFlag)
							{
								query += "and type in (" + 
										BDConstents.INOUT_TYPE + ", " +
										BDConstents.OUTIN_TYPE + ", " +
										BDConstents.MYBANK_INOUT_TYPE + ") ";
							}
							// 없음
							else
							{
								
							}
						}
					}
				}
					
				if ( ! (searchBankBook == null || searchBankBook.equals("조건 없음") || searchBankBook.equals("목록 없음") || searchBankBook.length() == 0))
				{
					searchName += searchBankBook;
				}
				
				if ( ! (searchCheckCard == null || searchCheckCard.equals("조건 없음") || searchCheckCard.equals("목록 없음") || searchCheckCard.length() == 0))
				{
					if ( ! (searchName == null || searchName.equals("조건 없음") || searchName.equals("목록 없음") || searchName.length() == 0))
					{
						searchName += ", " + searchCheckCard;
					}
					else
					{
						searchName += searchCheckCard;
					}
				}
				
				if ( ! (searchCreditCard == null || searchCreditCard.equals("조건 없음") || searchCreditCard.equals("목록 없음") || searchCreditCard.length() == 0))
				{
					if ( ! (searchName == null || searchName.equals("조건 없음") || searchName.equals("목록 없음") || searchName.length() == 0))
					{
						searchName += ", " + searchCreditCard;
					}
					else
					{
						searchName += searchCreditCard;
					}
				}
				
				if ( ! (searchName == null || searchName.equals("조건 없음") || searchName.equals("목록 없음") || searchName.length() == 0))
				{
					searchName = searchName.replaceAll(", ", "', '");
					query += "and moneykind in ('" + searchName + "') ";
				}
				
				if ( ! (searchMemo == null || searchMemo.equals("조건 없음") || searchMemo.equals("목록 없음") || searchMemo.length() == 0))
				{
					query += "and memo like '%" + searchMemo + "%' ";
				}
			}
			
			if (inoutFlag == StatsActivity.STATS_IN)
			{ // 통계 월별 수입
				query = query + "and inmoney not in ('0') and type not in (" + 
							BDConstents.INOUT_TYPE + ", " +
							BDConstents.OUTIN_TYPE + ", " +
							BDConstents.MYBANK_INOUT_TYPE + ")";
				
//				query = query + "UNION ALL "
//						   + "SELECT * FROM in_out WHERE date >= " + firstDate
//			 			   + " and date <= " + lastDate
//			 			   + " and category in ('" 
//			 			   + BDConstents.CATEGORY_SUSUMONEY + "')";
			}
			else if (inoutFlag == StatsActivity.STATS_OUT)
			{ // 통계 월별 지출
				query = query + "and inmoney in ('0') and (outmoney not in ('0') or postmoney not in ('0')) and type not in (" + 
							BDConstents.INOUT_TYPE + ", " +
							BDConstents.OUTIN_TYPE + ", " +
							BDConstents.MYBANK_INOUT_TYPE + ") and category not in ('"+ BDConstents.CATEGORY_POST_OUT + "')";
				
				query = query + "UNION ALL "
						   + "SELECT * FROM in_out WHERE date >= " + firstDate
			 			   + " and date <= " + lastDate
			 			   + " and category in ('" 
			 			   + BDConstents.CATEGORY_SUSUMONEY + "')";
			}
			else if (categoryFlag == StatsActivity.STATS_IN)
			{ // 통계 수입 카테고리
				query = query + "and inmoney not in ('0') " +
						"and category in ('" + categoryStr + "') and type not in (" + 
							BDConstents.INOUT_TYPE + ", " +
							BDConstents.OUTIN_TYPE + ", " +
							BDConstents.MYBANK_INOUT_TYPE + ")";
				
//				query = query + "UNION ALL "
//						   + "SELECT * FROM in_out WHERE date >= " + firstDate
//			 			   + " and date <= " + lastDate
//			 			   + " and category in ('" 
//			 			   + BDConstents.CATEGORY_SUSUMONEY + "')";
			}
			else if (categoryFlag == StatsActivity.STATS_OUT)
			{ // 통계 지출 카테고리
				
				if (categoryStr.equals(BDConstents.CATEGORY_SUSUMONEY))
				{
					query = query + "and inmoney in ('0') " 
				 			   + " and category in ('" 
				 			   + BDConstents.CATEGORY_SUSUMONEY + "')";
				}
				else
				{
					query = query + "and inmoney in ('0') and (outmoney not in ('0') or postmoney not in ('0')) " +
							"and category in ('" + categoryStr + "') and type not in (" + 
							BDConstents.INOUT_TYPE + ", " +
							BDConstents.OUTIN_TYPE + ", " +
							BDConstents.MYBANK_INOUT_TYPE + ") and category not in ('"+ BDConstents.CATEGORY_POST_OUT + "')";
				}
				
//				query = query + "UNION ALL "
//						   + "SELECT * FROM in_out WHERE date >= " + firstDate
//			 			   + " and date <= " + lastDate
//			 			   + " and category in ('" 
//			 			   + BDConstents.CATEGORY_SUSUMONEY + "')";
			}
			else if (categoryFlag == StatsActivity.STATS_MOVE)
			{ // 통계 이동 카테고리
				query = query + "and category in ('" + categoryStr + "') and type in (" + 
							BDConstents.INOUT_TYPE + ", " +
							BDConstents.OUTIN_TYPE + ", " +
							BDConstents.MYBANK_INOUT_TYPE + ")";
			}
			else if (categoryFlag == StatsActivity.STATS_ASSET_MANAGER)
			{
				typeFlag = getIntent().getIntExtra(StatsAssetActivity.TYPE_FLAG, 0);
				assetFlag = getIntent().getIntExtra(StatsAssetActivity.ASSET_FLAG, 0);
				
				String subQuery = "";
				
				if (assetFlag == 0)
				{
					if (typeFlag != 2)
					{
						subQuery += "and type = " + 
								BDConstents.BANK_TYPE + 
								" ";
					}
					else
					{
						subQuery += "and linktype = " + 
								BDConstents.BANK_TYPE + 
								" ";
					}
				}
				else if (assetFlag == 1)
				{
					if (typeFlag != 2)
					{
						subQuery += "and type = " + 
								BDConstents.CHECK_TYPE +  
								" ";
					}
					else
					{
						subQuery += "and linktype = " + 
								BDConstents.CHECK_TYPE +  
								" ";
					}
				}
				else if (assetFlag == 2)
				{
					if (typeFlag != 2)
					{
						subQuery += "and type = " + 
								BDConstents.CREDIT_TYPE +  
								" ";
					}
					else
					{
						subQuery += "and linktype = " + 
								BDConstents.CREDIT_TYPE +  
								" ";
					}
				}
				else if (assetFlag == 3)
				{
				}
				
				if (typeFlag == 0)
				{
					// 통계 지출 자산
//					if (categoryStr.equals(BDConstents.CATEGORY_SUSUMONEY))
//					{
//						query = query + "and inmoney in ('0') and moneykind in ('" + moneykindStr + "')" 
//					 			   + " and category in ('" 
//					 			   + BDConstents.CATEGORY_SUSUMONEY + "')";
//					}
//					else
//					{
//						query = query + "and inmoney in ('0') and (outmoney not in ('0') or postmoney not in ('0')) " +
//								"and moneykind in ('" + moneykindStr + "') and type not in (" + 
//								BDConstents.INOUT_TYPE + ", " +
//								BDConstents.OUTIN_TYPE + ", " +
//								BDConstents.MYBANK_INOUT_TYPE + ") and category not in ('"+ BDConstents.CATEGORY_POST_OUT + "')";
//					}
					
					tempQuery = query + "and inmoney in ('0') and moneykind in ('" + moneykindStr + "')" 
							+ " and category in ('" 
							+ BDConstents.CATEGORY_SUSUMONEY + "')";
					
					query = query + "and inmoney in ('0') and (outmoney not in ('0') or postmoney not in ('0')) " +
							"and moneykind in ('" + moneykindStr + "') and type not in (" + 
							BDConstents.INOUT_TYPE + ", " +
							BDConstents.OUTIN_TYPE + ", " +
							BDConstents.MYBANK_INOUT_TYPE + ") " + subQuery + ";";
				}
				else if (typeFlag == 1)
				{
					// 통계 수입 자산
					query = query + "and inmoney not in ('0') and moneykind in ('" + moneykindStr + "')" +
								"and type not in (" + 
								BDConstents.INOUT_TYPE + ", " +
								BDConstents.OUTIN_TYPE + ", " +
								BDConstents.MYBANK_INOUT_TYPE + ")" + subQuery;
				}
				else if (typeFlag == 2)
				{
					// 통계 이동 자산
					
					// 현금일 경우
					if (assetFlag == 3)
					{
						if (moneykindStr.equals(BDConstents.BANK_TO_REAL))
						{
							query = query + "and type in (" + BDConstents.INOUT_TYPE + ")";
						}
						else if (moneykindStr.equals(BDConstents.REAL_TO_BANK))
						{
							query = query + "and type in (" + BDConstents.OUTIN_TYPE + ")";
						}
					}
					else
					{
						query = query + "and moneykind in ('" + moneykindStr + "') and type in (" + 
								BDConstents.INOUT_TYPE + ", " +
								BDConstents.OUTIN_TYPE + ", " +
								BDConstents.MYBANK_INOUT_TYPE + ") " + subQuery;
					}
				}
			}
		}
		
		if (categoryFlag == StatsActivity.STATS_ASSET_MANAGER)
		{
			if (typeFlag == 0)
			{
				// 통계 지출 자산
				if (categoryStr.equals(BDConstents.CATEGORY_SUSUMONEY))
				{
					query = "SELECT * FROM (" + query + " UNION ALL " + tempQuery + ")";
				}
			}
		}
		
		// 검색조회에서 수수료 카테고리가 선택 됬을 경우 수수료도 조회한다.
		if (categorys != null)
		{
			for (int j = 0; j < categorys.length; j++)
			{
				if (categorys[j].equals(BDConstents.CATEGORY_SUSUMONEY))
				{
					query += " UNION ALL "
							+ "SELECT * FROM in_out WHERE date >= " +
							firstDate + " and date <= " +
							lastDate + " and category in ('" 
							+ BDConstents.CATEGORY_SUSUMONEY + "')";
					break;
				}
			}
		}
		
		query += " ORDER BY date DESC, type ASC";
		
//		Log.e("selectQuery", query);
		
		sql.selectMapTile(this, query, new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				ArrayList<SelectData> list = new ArrayList<SelectData>();
				SelectDayData monthData = new SelectDayData();
				
//				int dayInMoney = 0;
//				int dayOutMoney = 0;
//				int dayPostMoney = 0;
				BigDecimal dayInMoney = BigDecimal.ZERO;
				BigDecimal dayOutMoney = BigDecimal.ZERO;
				BigDecimal dayPostMoney = BigDecimal.ZERO;
				
				// 자식뷰의 설명을 셋팅한다.
//				SelectData firstData = new SelectData();
//				firstData.setType("-1");
//				firstData.setCategory("카테고리");
//				firstData.setInMoney("수입/지출");
//				list.add(firstData);
				
				int id = c.getColumnIndex("id");
				int category = c.getColumnIndex("category");
				int memo = c.getColumnIndex("memo");
				int inmoney = c.getColumnIndex("inmoney");
				int outmoney = c.getColumnIndex("outmoney");
				int date = c.getColumnIndex("date");
				int moneykind = c.getColumnIndex("moneykind");
				int postmoneykind = c.getColumnIndex("postmoneykind");
				int postmoney = c.getColumnIndex("postmoney");
				int type = c.getColumnIndex("type");
				int linkid = c.getColumnIndex("linkid");
				int linktype = c.getColumnIndex("linktype");
				int deleteyn = c.getColumnIndex("deleteyn");
				
				c.moveToFirst();
				
				if (c.getCount() > 0)
				{
					tempDate = c.getInt(date);
				}
				
				for (int i = 0; i < c.getCount(); i++)
				{
					try
					{
						// 날짜가 다른 경우 다음 리스트로 셋팅한다.
						if (tempDate != c.getInt(date))
						{
							monthData.setDayInMoney(dayInMoney + "");
							monthData.setDayOutMoney(dayOutMoney + "");
							monthData.setDayPostMoney(dayPostMoney + "");
							monthData.setToDay(tempDate + "");
							
//						if (list.size() >= 2)
//						{
//							list = sortList(list);
//						}
							
							monthData.setDayList(list);
							dayList.add(monthData);
							
							list = new ArrayList<SelectData>();
							monthData = new SelectDayData();
							tempDate = c.getInt(date);
								
//						SelectData tempData = new SelectData();
//						tempData.setType("-1");
//						tempData.setCategory("카테고리");
//						tempData.setInMoney("수입/지출");
//						list.add(tempData);
							
							dayInMoney = BigDecimal.ZERO;
							dayOutMoney = BigDecimal.ZERO;
							dayPostMoney = BigDecimal.ZERO;
						}
						
						SelectData data = new SelectData();
						data.setId(c.getInt(id) + "");
						data.setCategory(c.getString(category));
						String strMemo = c.getString(memo);
						if (strMemo != null && strMemo.length() > 4)
						{
							data.setMemo(strMemo.substring(0, 5)+"..");
						}
						else
						{
							data.setMemo(strMemo);
						}
						
						data.setInMoney(c.getString(inmoney));
						data.setOutMoney(c.getString(outmoney));
						data.setPostMoney(c.getString(postmoney));
						data.setDate(c.getInt(date) + "");
						data.setMoneyKind(c.getString(moneykind));
						data.setPostMoneyKind(c.getString(postmoneykind));
						data.setType(c.getInt(type) + "");
						data.setLinkId(c.getInt(linkid) + "");
						data.setLinktype(c.getInt(linktype) + "");
						data.setDeleteYn(c.getInt(deleteyn) + "");
						
						list.add(data);
						
						// 부채 설정 여부에 따라서 조회에서도 수입, 지출을 합계 하지 않는다.
				    	if (fanOkNoFlag != 0)
						{
							if (data.getType().equals(BDConstents.FAN_TYPE))
							{
								c.moveToNext();
								continue;
							}
						}
						
						if (categoryFlag == StatsActivity.STATS_MOVE 
								|| (categoryFlag == StatsActivity.STATS_ASSET_MANAGER && typeFlag == 2))
						{
							if (data.getType().equals(BDConstents.INOUT_TYPE))
							{
								dayPostMoney = dayPostMoney.add(new BigDecimal(c.getString(outmoney)));
								dayPostMoney = dayPostMoney.add(new BigDecimal(c.getString(postmoney)));
								
								totalCard = totalCard.add(new BigDecimal(data.getOutMoney()));
								totalCard = totalCard.add(new BigDecimal(data.getPostMoney()));
							}
							else if (data.getType().equals(BDConstents.OUTIN_TYPE))
							{
								dayPostMoney = dayPostMoney.add(new BigDecimal(c.getString(inmoney)));
								
								totalCard = totalCard.add(new BigDecimal(data.getInMoney()));
							}
							else if (data.getType().equals(BDConstents.MYBANK_INOUT_TYPE))
							{
								dayPostMoney = dayPostMoney.add(new BigDecimal(c.getString(outmoney)));
								dayPostMoney = dayPostMoney.add(new BigDecimal(c.getString(postmoney)));
								
								totalCard = totalCard.add(new BigDecimal(data.getOutMoney()));
								totalCard = totalCard.add(new BigDecimal(data.getPostMoney()));
							}
						}
						else if (!c.getString(type).equals(BDConstents.INOUT_TYPE) 
								&& !c.getString(type).equals(BDConstents.OUTIN_TYPE)
								&& !c.getString(type).equals(BDConstents.MYBANK_INOUT_TYPE))
						{
							dayInMoney = dayInMoney.add(new BigDecimal(c.getString(inmoney)));
							dayOutMoney = dayOutMoney.add(new BigDecimal(c.getString(outmoney)));
							dayPostMoney = dayPostMoney.add(new BigDecimal(c.getString(postmoney)));
							
							totalIn = totalIn.add(new BigDecimal(data.getInMoney()));
							totalOut = totalOut.add(new BigDecimal(data.getOutMoney()));
							totalCard = totalCard.add(new BigDecimal(data.getPostMoney()));
						}
						else
						{
							if (c.getString(linktype).equals("3"))
							{
//							dayPostMoney = dayPostMoney + Integer.parseInt(c.getString(postmoney));
								dayPostMoney = dayPostMoney.add(new BigDecimal(c.getString(postmoney)));
								
//							totalCard = totalCard + Integer.parseInt(data.getPostMoney());
								totalCard = totalCard.add(new BigDecimal(data.getPostMoney()));
							}
							else if (c.getString(category).equals(BDConstents.CATEGORY_SUSUMONEY))
							{
//							dayOutMoney = dayOutMoney + Integer.parseInt(c.getString(outmoney));
								dayOutMoney = dayOutMoney.add(new BigDecimal(c.getString(outmoney)));
								
//							totalOut = totalOut + Integer.parseInt(data.getOutMoney());
								totalOut = totalOut.add(new BigDecimal(data.getOutMoney()));
							}
						}
						
						c.moveToNext();
					} catch (Exception e)
					{
						c.moveToNext();
					}
				}
				
				monthData.setDayInMoney(dayInMoney.toString());
				monthData.setDayOutMoney(dayOutMoney.toString());
				monthData.setDayPostMoney(dayPostMoney.toString());
				monthData.setToDay(tempDate + "");
				
//				if (list.size() >= 2)
//				{
//					list = sortList(list);
//				}
				
				monthData.setDayList(list);
				dayList.add(monthData);
				
				if (c.getCount() < 1)
				{
					dayList.clear();
				}
			}
		});
	}
	
	private ArrayList<SelectData> sortList(ArrayList<SelectData> list)
	{
		ArrayList<SelectData> sortedList = new ArrayList<SelectData>();
		ArrayList<SelectData> outmoneyList = new ArrayList<SelectData>();
		ArrayList<SelectData> postmoneyList = new ArrayList<SelectData>();
		ArrayList<SelectData> inmoneyList = new ArrayList<SelectData>();
		ArrayList<SelectData> cashdrawingList = new ArrayList<SelectData>();
		
		SelectData maxData = new SelectData();
		maxData.setId(list.get(0).getId());
		maxData.setCategory(list.get(0).getCategory());
		maxData.setMemo(list.get(0).getMemo());
		maxData.setInMoney(list.get(0).getInMoney());
		maxData.setOutMoney(list.get(0).getOutMoney());
		maxData.setPostMoney(list.get(0).getPostMoney());
		maxData.setDate(list.get(0).getDate());
		maxData.setMoneyKind(list.get(0).getMoneyKind());
		maxData.setPostMoneyKind(list.get(0).getPostMoneyKind());
		maxData.setType(list.get(0).getType());
		maxData.setLinkId(list.get(0).getLinkId());
		maxData.setLinktype(list.get(0).getLinktype());
		maxData.setDeleteYn(list.get(0).getDeleteYn());
		
		int maxIndex = -1;
		int size = list.size();
		
		for (int i=0; i<size; i++)
		{
			for (int j=0; j<size; j++)
			{
				if (list.get(j).getType().equals("0") || list.get(j).getType().equals("1") || 
						list.get(j).getType().equals("2") || list.get(j).getType().equals("3") || 
						list.get(j).getType().equals("5") || list.get(j).getType().equals("7") )
				{
					if (Integer.parseInt(maxData.getOutMoney()) < Integer.parseInt(list.get(j).getOutMoney()))
					{
						maxData.setId(list.get(j).getId());
						maxData.setCategory(list.get(j).getCategory());
						maxData.setMemo(list.get(j).getMemo());
						maxData.setInMoney(list.get(j).getInMoney());
						maxData.setOutMoney(list.get(j).getOutMoney());
						maxData.setPostMoney(list.get(j).getPostMoney());
						maxData.setDate(list.get(j).getDate());
						maxData.setMoneyKind(list.get(j).getMoneyKind());
						maxData.setPostMoneyKind(list.get(j).getPostMoneyKind());
						maxData.setType(list.get(j).getType());
						maxData.setLinkId(list.get(j).getLinkId());
						maxData.setLinktype(list.get(j).getLinktype());
						maxData.setDeleteYn(list.get(j).getDeleteYn());
						
						maxIndex = j;
					}
				}
			}
			
			if (Integer.parseInt(maxData.getOutMoney()) > 0)
			{
				SelectData tempData = new SelectData();
				tempData.setId(maxData.getId());
				tempData.setCategory(maxData.getCategory());
				tempData.setMemo(maxData.getMemo());
				tempData.setInMoney(maxData.getInMoney());
				tempData.setOutMoney(maxData.getOutMoney());
				tempData.setPostMoney(maxData.getPostMoney());
				tempData.setDate(maxData.getDate());
				tempData.setMoneyKind(maxData.getMoneyKind());
				tempData.setPostMoneyKind(maxData.getPostMoneyKind());
				tempData.setType(maxData.getType());
				tempData.setLinkId(maxData.getLinkId());
				tempData.setLinktype(maxData.getLinktype());
				tempData.setDeleteYn(maxData.getDeleteYn());
				
				outmoneyList.add(tempData);
				
				maxData.setOutMoney("0");
				list.get(maxIndex).setOutMoney("0");
			}
		}
		
		for (int j=0; j<outmoneyList.size(); j++)
		{
			sortedList.add(outmoneyList.get(j));
		}
		
		for (int i=0; i<size; i++)
		{
			for (int j=0; j<size; j++)
			{
				if (list.get(j).getType().equals("0") || list.get(j).getType().equals("1") || 
						list.get(j).getType().equals("2") || list.get(j).getType().equals("3") || 
						list.get(j).getType().equals("5") || list.get(j).getType().equals("7") )
				{
					if (Integer.parseInt(maxData.getPostMoney()) < Integer.parseInt(list.get(j).getPostMoney()))
					{
						maxData.setId(list.get(j).getId());
						maxData.setCategory(list.get(j).getCategory());
						maxData.setMemo(list.get(j).getMemo());
						maxData.setInMoney(list.get(j).getInMoney());
						maxData.setOutMoney(list.get(j).getOutMoney());
						maxData.setPostMoney(list.get(j).getPostMoney());
						maxData.setDate(list.get(j).getDate());
						maxData.setMoneyKind(list.get(j).getMoneyKind());
						maxData.setPostMoneyKind(list.get(j).getPostMoneyKind());
						maxData.setType(list.get(j).getType());
						maxData.setLinkId(list.get(j).getLinkId());
						maxData.setLinktype(list.get(j).getLinktype());
						maxData.setDeleteYn(list.get(j).getDeleteYn());
						
						maxIndex = j;
					}
				}
			}
			
			if (Integer.parseInt(maxData.getPostMoney()) > 0)
			{
				SelectData tempData = new SelectData();
				tempData.setId(maxData.getId());
				tempData.setCategory(maxData.getCategory());
				tempData.setMemo(maxData.getMemo());
				tempData.setInMoney(maxData.getInMoney());
				tempData.setOutMoney(maxData.getOutMoney());
				tempData.setPostMoney(maxData.getPostMoney());
				tempData.setDate(maxData.getDate());
				tempData.setMoneyKind(maxData.getMoneyKind());
				tempData.setPostMoneyKind(maxData.getPostMoneyKind());
				tempData.setType(maxData.getType());
				tempData.setLinkId(maxData.getLinkId());
				tempData.setLinktype(maxData.getLinktype());
				tempData.setDeleteYn(maxData.getDeleteYn());
				
				postmoneyList.add(tempData);
				
				maxData.setPostMoney("0");
				list.get(maxIndex).setPostMoney("0");
			}
		}
		
		for (int j=0; j<postmoneyList.size(); j++)
		{
			sortedList.add(postmoneyList.get(j));
		}
		
		for (int i=0; i<size; i++)
		{
			for (int j=0; j<size; j++)
			{
				if (list.get(j).getType().equals("0") || list.get(j).getType().equals("1") || 
						list.get(j).getType().equals("2") || list.get(j).getType().equals("3") || 
						list.get(j).getType().equals("5") || list.get(j).getType().equals("7") )
				{
					if (Integer.parseInt(maxData.getInMoney()) < Integer.parseInt(list.get(j).getInMoney()))
					{
						maxData.setId(list.get(j).getId());
						maxData.setCategory(list.get(j).getCategory());
						maxData.setMemo(list.get(j).getMemo());
						maxData.setInMoney(list.get(j).getInMoney());
						maxData.setOutMoney(list.get(j).getOutMoney());
						maxData.setPostMoney(list.get(j).getPostMoney());
						maxData.setDate(list.get(j).getDate());
						maxData.setMoneyKind(list.get(j).getMoneyKind());
						maxData.setPostMoneyKind(list.get(j).getPostMoneyKind());
						maxData.setType(list.get(j).getType());
						maxData.setLinkId(list.get(j).getLinkId());
						maxData.setLinktype(list.get(j).getLinktype());
						maxData.setDeleteYn(list.get(j).getDeleteYn());
						
						maxIndex = j;
					}
				}
			}
			
			if (Integer.parseInt(maxData.getInMoney()) > 0)
			{
				SelectData tempData = new SelectData();
				tempData.setId(maxData.getId());
				tempData.setCategory(maxData.getCategory());
				tempData.setMemo(maxData.getMemo());
				tempData.setInMoney(maxData.getInMoney());
				tempData.setOutMoney(maxData.getOutMoney());
				tempData.setPostMoney(maxData.getPostMoney());
				tempData.setDate(maxData.getDate());
				tempData.setMoneyKind(maxData.getMoneyKind());
				tempData.setPostMoneyKind(maxData.getPostMoneyKind());
				tempData.setType(maxData.getType());
				tempData.setLinkId(maxData.getLinkId());
				tempData.setLinktype(maxData.getLinktype());
				tempData.setDeleteYn(maxData.getDeleteYn());
				
				inmoneyList.add(tempData);
				
				maxData.setInMoney("0");
				list.get(maxIndex).setInMoney("0");
			}
		}
		
		for (int j = 0; j < inmoneyList.size(); j++)
		{
			sortedList.add(inmoneyList.get(j));
		}
		
		for (int i=0; i<size; i++)
		{
			for (int j=0; j<size; j++)
			{
				if (list.get(j).getType().equals("4") || list.get(j).getType().equals("6")) 
				{
					if (Integer.parseInt(maxData.getOutMoney()) < Integer.parseInt(list.get(j).getOutMoney()))
					{
						maxData.setId(list.get(j).getId());
						maxData.setCategory(list.get(j).getCategory());
						maxData.setMemo(list.get(j).getMemo());
						maxData.setInMoney(list.get(j).getInMoney());
						maxData.setOutMoney(list.get(j).getOutMoney());
						maxData.setPostMoney(list.get(j).getPostMoney());
						maxData.setDate(list.get(j).getDate());
						maxData.setMoneyKind(list.get(j).getMoneyKind());
						maxData.setPostMoneyKind(list.get(j).getPostMoneyKind());
						maxData.setType(list.get(j).getType());
						maxData.setLinkId(list.get(j).getLinkId());
						maxData.setLinktype(list.get(j).getLinktype());
						maxData.setDeleteYn(list.get(j).getDeleteYn());
						
						maxIndex = j;
					}
				}
			}
			
			if (Integer.parseInt(maxData.getOutMoney()) > 0)
			{
				SelectData tempData = new SelectData();
				tempData.setId(maxData.getId());
				tempData.setCategory(maxData.getCategory());
				tempData.setMemo(maxData.getMemo());
				tempData.setInMoney(maxData.getInMoney());
				tempData.setOutMoney(maxData.getOutMoney());
				tempData.setPostMoney(maxData.getPostMoney());
				tempData.setDate(maxData.getDate());
				tempData.setMoneyKind(maxData.getMoneyKind());
				tempData.setPostMoneyKind(maxData.getPostMoneyKind());
				tempData.setType(maxData.getType());
				tempData.setLinkId(maxData.getLinkId());
				tempData.setLinktype(maxData.getLinktype());
				tempData.setDeleteYn(maxData.getDeleteYn());
				
				cashdrawingList.add(tempData);
				
				maxData.setOutMoney("0");
				maxData.setInMoney("0");
				list.get(maxIndex).setOutMoney("0");
				list.get(maxIndex).setInMoney("0");
			}
		}
		
		for (int j=0; j<cashdrawingList.size(); j++)
		{
			sortedList.add(cashdrawingList.get(j));
		}
		
		return sortedList;
	}
	
	private void initClickListener()
	{
		findViewById(R.id.select_button_pre).setOnClickListener(new OnClickListener() 
		{
			@Override
			public void onClick(View v) 
			{
				setIsOpenData();
				
				if (searchFlag)
				{
					int [] startDates = BDUtil.getDateSet(searchStartDate);
					int [] endDates = BDUtil.getDateSet(searchEndDate);
					
					Calendar cal1 = Calendar.getInstance();
					cal1.set(startDates[0], startDates[1]-1, startDates[2]);
					
					Calendar cal2 = Calendar.getInstance();
					cal2.set(endDates[0], endDates[1]-1, endDates[2]);
					
					boolean maxFlag = false;
					
					if (startDates[2] == 1 
							&& endDates[2] == cal2.getActualMaximum(Calendar.DAY_OF_MONTH))
					{
						maxFlag = true;
					}
					
					cal1.add(Calendar.MONTH, -1);
					cal2.add(Calendar.MONTH, -1);
					
					searchStartDate = BDUtil.getDateDB(
							cal1.get(Calendar.YEAR), cal1.get(Calendar.MONTH)+1, cal1.get(Calendar.DAY_OF_MONTH));
					
					if (maxFlag)
					{
						searchEndDate = BDUtil.getDateDB(
								cal2.get(Calendar.YEAR), cal2.get(Calendar.MONTH)+1, cal2.getActualMaximum(Calendar.DAY_OF_MONTH));
					}
					else
					{
						searchEndDate = BDUtil.getDateDB(
								cal2.get(Calendar.YEAR), cal2.get(Calendar.MONTH)+1, cal2.get(Calendar.DAY_OF_MONTH));
					}
				}
				else if (mainFlag)
				{
					mainQuery.setLeftMonth();
				}
				else
				{
					month--;
					
					if (month < 0) 
					{
						year--;
						month = 11;
					}
				}
				
				BDUtil.startLeftDegrees(findViewById(R.id.selectMonthLayout)).setAnimationListener(new AnimationListener()
				{
					@Override
					public void onAnimationStart(Animation animation)
					{
					}
					
					@Override
					public void onAnimationRepeat(Animation animation)
					{
					}
					
					@Override
					public void onAnimationEnd(Animation animation)
					{
						new ShowDialog().execute(null);
					}
				});
			}
		});
		
		findViewById(R.id.select_button_next).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) 
			{
				setIsOpenData();
				
				if (searchFlag)
				{
					int [] startDates = BDUtil.getDateSet(searchStartDate);
					int [] endDates = BDUtil.getDateSet(searchEndDate);
					
					Calendar cal1 = Calendar.getInstance();
					cal1.set(startDates[0], startDates[1]-1, startDates[2]);
					
					Calendar cal2 = Calendar.getInstance();
					cal2.set(endDates[0], endDates[1]-1, endDates[2]);
					
					boolean maxFlag = false;
					
					if (startDates[2] == 1 
							&& endDates[2] == cal2.getActualMaximum(Calendar.DAY_OF_MONTH))
					{
						maxFlag = true;
					}
					
					cal1.add(Calendar.MONTH, 1);
					cal2.add(Calendar.MONTH, 1);
					
					searchStartDate = BDUtil.getDateDB(
							cal1.get(Calendar.YEAR), cal1.get(Calendar.MONTH)+1, cal1.get(Calendar.DAY_OF_MONTH));
					
					if (maxFlag)
					{
						searchEndDate = BDUtil.getDateDB(
								cal2.get(Calendar.YEAR), cal2.get(Calendar.MONTH)+1, cal2.getActualMaximum(Calendar.DAY_OF_MONTH));
					}
					else
					{
						searchEndDate = BDUtil.getDateDB(
								cal2.get(Calendar.YEAR), cal2.get(Calendar.MONTH)+1, cal2.get(Calendar.DAY_OF_MONTH));
					}
				}
				else if (mainFlag)
				{
					mainQuery.setRightMonth();
				}
				else
				{
					month++;
					
					if (month > 11) 
					{
						year++;
						month = 0;
					}
				}
				
				BDUtil.startRightDegrees(findViewById(R.id.selectMonthLayout)).setAnimationListener(new AnimationListener()
				{
					@Override
					public void onAnimationStart(Animation animation)
					{
					}
					
					@Override
					public void onAnimationRepeat(Animation animation)
					{
					}
					
					@Override
					public void onAnimationEnd(Animation animation)
					{
						new ShowDialog().execute(null);
					}
				});
			}
		});
	}
	
	private ExpandableListView.OnChildClickListener onChildClickListener = new OnChildClickListener()
	{
		@Override
		public boolean onChildClick(ExpandableListView parent, View v,
				int groupPosition, int childPosition, long id)
		{
//			if (childPosition == 0)
//			{
//				return false;
//			}
			
			SelectData data = dayList.get(groupPosition).getDayList().get(childPosition);
			
			Intent intent = new Intent(SelectActivity.this, SelectInfoActivity.class);
			intent.putExtra(SELECT_DATA, data);
			startActivity(intent);
			return false;
		}
	};
	
	private void setOpen()
	{
		if (openArrayList.size() < 1)
		{
			return;
		}
		
		IsOpenData data = null;
		
		String date = ((TextView) findViewById(R.id.select_text_today))
				.getText().toString();
		
		for (int i = 0; i < openArrayList.size(); i++)
		{
			data = openArrayList.get(i);
			
			if (date.equals(data.getDate()))
			{
				break;
			}
			else
			{
				data = null;
			}
		}
		
		if (data == null)
		{
			return;
		}
		
		int [] openArray = data.getIsOpenArry();
		
		ExpandableListAdapter adapter = listView.getExpandableListAdapter();
		
		if (adapter == null)
		{
			return;
		}
		
		try
		{
			for (int i = 0; i < adapter.getGroupCount(); i++)
			{
				int flag = openArray[i];
				
				if (flag == 1)
				{
					listView.collapseGroup(i);
					listView.expandGroup(i);
				}
			}
		} catch (Exception e)
		{
			return;
		}
	}
	
	private class SelectExpandableAdapter extends BaseExpandableListAdapter
	{
		private ArrayList<SelectDayData> list = new ArrayList<SelectDayData>();
		
		private SelectExpandableAdapter(ArrayList<SelectDayData> list)
		{
			super();
			this.list = list;
		}

		@Override
		public Object getChild(int groupPosition, int childPosition)
		{
			return this.list.get(groupPosition).getDayList().get(childPosition);
		}

		@Override
		public long getChildId(int groupPosition, int childPosition)
		{
			return 0;
		}

		@Override
		public View getChildView(int groupPosition, int childPosition,
				boolean isLastChild, View convertView, ViewGroup parent)
		{
			View v = convertView;
			
			if (v == null)
			{
				LayoutInflater li = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
				v = li.inflate(R.layout.list_item_select, null);
			}
			
			SelectData data = list.get(groupPosition).getDayList().get(childPosition);
			
			BDTextView type = (BDTextView) v.findViewById(R.id.listSelectType);
			BDTextView category = (BDTextView) v.findViewById(R.id.listSelectCategory);
			BDTextView memo = (BDTextView) v.findViewById(R.id.listSelectMemo);
			BDTextView money = (BDTextView) v.findViewById(R.id.listSelectMoney);
			
			if (data.getType().equals("-1"))
			{
				type.setText(BDConstents.TYPE_TITLE);
				money.setText(data.getInMoney());
			}
			else if (data.getType().equals(BDConstents.REAL_TYPE))
			{
				type.setText(BDConstents.REAL_MONEY);
				setMoneyData(data, type, money);
			}
			else if (data.getType().equals(BDConstents.BANK_TYPE))
			{
				type.setText(BDConstents.BANK_MONEY);
				setMoneyData(data, type, money);
			}
			else if (data.getType().equals(BDConstents.CHECK_TYPE))
			{
				type.setText(BDConstents.CHECK_CARD);
				setMoneyData(data, type, money);
			}
			else if (data.getType().equals(BDConstents.CREDIT_TYPE))
			{
				type.setText(BDConstents.CREDIT_CARD);
				money.setText(BDUtil.getWon(data.getPostMoney()));
				money.setTextColor(postMoneyColor);
			}
			else if (data.getType().equals(BDConstents.INOUT_TYPE))
			{
				type.setText(BDConstents.BANK_TO_REAL);
				
				if (data.getCategory().equals("수수료"))
				{
					if (data.getLinktype().equals(BDConstents.CREDIT_TYPE))
					{
						money.setText("-" + BDUtil.getWon(data.getPostMoney()));
						money.setTextColor(postMoneyColor);
					}
					else
					{
						money.setText(BDUtil.getWon(data.getOutMoney()));
						money.setTextColor(outMoneyColor);
					}
				}
				else if (data.getLinktype().equals(BDConstents.CREDIT_TYPE))
				{
					money.setText("±" + BDUtil.getWon(data.getPostMoney()));
					money.setTextColor(postMoneyColor);
				}
				else
				{
					money.setText("±" + BDUtil.getWon(data.getOutMoney()));
					money.setTextColor(cashDrawingColor);
				}
			}
			else if (data.getType().equals(BDConstents.OUTIN_TYPE))
			{
				type.setText(BDConstents.REAL_TO_BANK);
				
				money.setText("±" + BDUtil.getWon(data.getOutMoney()));
				money.setTextColor(cashDrawingColor);
			}
			else if (data.getType().equals(BDConstents.FAN_TYPE))
			{
				type.setText(BDConstents.FAN_MONEY);
				
				if (data.getLinktype().equals(BDConstents.CREDIT_TYPE))
				{
					money.setText(BDUtil.getWon(data.getPostMoney()));
					money.setTextColor(postMoneyColor);
				}
				else
				{
					setMoneyData(data, type, money);
				}
			}
			else if (data.getType().equals(BDConstents.MYBANK_INOUT_TYPE))
			{
				type.setText(BDConstents.MYBANK_INOUT);
				
				if (data.getLinktype().equals(BDConstents.CREDIT_TYPE))
				{
					money.setText(BDUtil.getWon(data.getPostMoney()));
					money.setTextColor(postMoneyColor);
				}
				else
				{
					setMoneyData(data, type, money);
				}
			}
			
			category.setText(data.getCategory());
			
			memo.setText(data.getMemo());
						
			return v;
		}

		@Override
		public int getChildrenCount(int groupPosition)
		{
			return this.list.get(groupPosition).getDayList().size();
		}

		@Override
		public Object getGroup(int groupPosition)
		{
			return this.list.get(groupPosition);
		}

		@Override
		public int getGroupCount()
		{
			return this.list.size();
		}

		@Override
		public long getGroupId(int groupPosition)
		{
			return 0;
		}

		@Override
		public View getGroupView(int groupPosition, boolean isExpanded,
				View convertView, ViewGroup parent)
		{
			View v = convertView;
			
			if (v == null)
			{
				LayoutInflater li = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
				v = li.inflate(R.layout.list_item_day_select, null);
			}
			
			SelectDayData data = list.get(groupPosition);
			
			BDTextView day = (BDTextView) v.findViewById(R.id.selectDayDate);
			BDTextView dayInMoney = (BDTextView) v.findViewById(R.id.selectDayInMoney);
			BDTextView dayOutMoney = (BDTextView) v.findViewById(R.id.selectDayOutMoney);
			BDTextView dayPostMoney = (BDTextView) v.findViewById(R.id.selectDayPostMoney);
			
			int date[] = BDUtil.getDateSet(data.getToDay());
			WeekDayClass weekDay = BDUtil.getWeekDayChinese(date[0], date[1]-1, date[2]);
			String dayStr = date[0]+"년 "+date[1]+"월 "+date[2]+"일 "+weekDay.getWeekDayStr();
			SpannableStringBuilder sp = new SpannableStringBuilder();
			sp.append(dayStr);
			sp.setSpan(new ForegroundColorSpan(weekDay.getWeekDayColor()), dayStr.indexOf("("), dayStr.indexOf(")")+1, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
			day.setText(sp);
			dayInMoney.setText(BDUtil.getWon(data.getDayInMoney()));
			dayOutMoney.setText(BDUtil.getWon(data.getDayOutMoney()));
			dayPostMoney.setText(BDUtil.getWon(data.getDayPostMoney()));
			
			if (categoryFlag == StatsActivity.STATS_MOVE || 
					(categoryFlag == StatsActivity.STATS_ASSET_MANAGER && typeFlag == 2))
			{
				dayInMoney.setVisibility(View.INVISIBLE);
				dayOutMoney.setVisibility(View.INVISIBLE);
				dayPostMoney.setTextColor(cashDrawingColor);
			}
			
			return v;
		}

		@Override
		public boolean hasStableIds()
		{
			return false;
		}

		@Override
		public boolean isChildSelectable(int groupPosition, int childPosition)
		{
			return true;
		}
		
		// 금액 데이터를 셋팅한다.
		private void setMoneyData(SelectData data, TextView type,
				TextView money)
		{
			if (data.getInMoney().equals("0"))
			{
				money.setText("-" + BDUtil.getWon(data.getOutMoney()));
				money.setTextColor(outMoneyColor);
			}
			else
			{
				money.setText("+" + BDUtil.getWon(data.getInMoney()));
				money.setTextColor(inMoneyColor);
			}
		}
	}
	
	private class IsOpenData
	{
		private String date = "";
		private int [] isOpenArry = null;
		
		public IsOpenData(){};
		
		public IsOpenData(int count)
		{
			this.date = "";
			this.isOpenArry = new int[count];
		}
		
		public String getDate()
		{
			return date;
		}
		public void setDate(String date)
		{
			this.date = date;
		}
		public int[] getIsOpenArry()
		{
			return isOpenArry;
		}
		public void setIsOpenArry(int[] isOpenArry)
		{
			this.isOpenArry = isOpenArry;
		}
	}
	
	/**
	 * 다이얼로그 뛰우기 
	 */
	private class ShowDialog extends AsyncTask<Integer, Integer, Integer>{
		ProgressDialog dialog = null;
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog = new ProgressDialog(SelectActivity.this);
			dialog.setCancelable(false);
			dialog.setMessage("Loading...");
			dialog.show();
		}
		
		@Override
		protected Integer doInBackground(Integer... arg0) {
			setSelectMonthData();
			
			return null;
		}
		
		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
			
			dialog.dismiss();
			
			if (listView.getFooterViewsCount() > 0)
			{
				listView.removeFooterView(resultView);
			}
			
			if (dayList.size() < 1)
			{
				listView.addFooterView(resultView);
				listView.setFooterDividersEnabled(false);
			}
			else
			{
				listView.setDividerHeight(0);
				listView.setOnChildClickListener(onChildClickListener);
			}
			
			SelectExpandableAdapter adapter = new SelectExpandableAdapter(dayList);
			listView.setAdapter(adapter);
			adapter.notifyDataSetChanged();
			
			setTextResult();
			
			setOpen();
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		menu.add(0, 2, 2, "입력");
		menu.add(0, 3, 3, "자산이동");
		
		return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		Intent intent = null;
		
		switch (item.getItemId()) 
		{
			case 2:
				intent = new Intent(this, InsertTabActivity.class);
				startActivity(intent);
				break;
			case 3:
				intent = new Intent(this, CashTabActivity.class);
				startActivity(intent);
				break;
			default:
				break;
		}
		
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void tipButton()
	{
		Intent intent = new Intent(this, TipInfoActivity.class);
		intent.putExtra(TipsActivity.TIP_REQUEST_KEY, TipsActivity.TIP_SELECT);
		startActivity(intent);
	}
}
